
package org.masterinftel.scrumpmt.activities;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import org.masterinftel.scrumpmt.Constants;
import org.masterinftel.scrumpmt.R;
import org.masterinftel.scrumpmt.ScrumApplication;
import org.masterinftel.scrumpmt.adapters.BacklogAdapter;
import org.masterinftel.scrumpmt.json.model.ColaboradorJSON;
import org.masterinftel.scrumpmt.json.model.ListColabAll;
import org.masterinftel.scrumpmt.json.model.TareaJSON;
import org.masterinftel.scrumpmt.protocol.Protocol;
import org.masterinftel.scrumpmt.util.UtilNetwork;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class BacklogActivity extends ListActivity {
    private List<TareaJSON> getTask() {

        return application.getTareas();
    }

    private ListView lstOpciones;
    private ScrumApplication application;
    private ProgressDialog progressDialog;
    private Context ctx;
    private AdapterContextMenuInfo info;
    private int selectedContextMenu;
    private Dialog dialog;
    private String URLFrontController;
    private List<TareaJSON> datos;

    // Manejador asincrono de las peticiones de las tareas
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            progressDialog.dismiss();
            switch (msg.what) {

                case 1:
                    // application.setSprints(respuesta.lSprint);
                    Intent intent = new Intent(ctx, AddToSprintActivity.class);
                    intent.putExtra("position", datos.get(selectedContextMenu).getId());
                    intent.putExtra("selected", selectedContextMenu);
                    startActivity(intent);
                    break;
                case 2:
                    startActivity(new Intent(ctx,
                            NewTaskActivity.class));
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("ScrumPMT - Backlog");
        // creamos variables utiles para la aplicacion
        ctx = this;
        application = (ScrumApplication) getApplication();
        datos = getTask();

        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(ctx);
        URLFrontController = prefs.getString(Constants.KEY_URL_PREFERENCE, "");

        ArrayAdapter<TareaJSON> adapter = new BacklogAdapter(this,
                getTask());

        setListAdapter(adapter);
        lstOpciones = this.getListView();

        // As� se ponen los fondos en las listView
        lstOpciones
                .setBackgroundDrawable(getResources().getDrawable(R.drawable.scrumpmtbackground));
        registerForContextMenu(lstOpciones);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        List<TareaJSON> datos = getTask();
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        menu.setHeaderTitle(datos.get(info.position).getDes());
        inflater.inflate(R.menu.backlogcontextmenu, menu);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.effort_backlog:
                // Utiliza Constants.LOGTAG para los tags de los logs Emilio!!
                Log.i(Constants.LOGTAG, "Lista["
                        + datos.get(info.position).getDes() + "]: esfuerzo pulsada!");
                dialog = new Dialog(BacklogActivity.this);
                dialog.setContentView(R.layout.taskeffort);
                dialog.setTitle(datos.get(info.position).getDes());
                dialog.setCancelable(true);

                // set up button
                Button buttoneffort = (Button) dialog.findViewById(R.id.BtAddEffort);
                buttoneffort.setOnClickListener(mAddEffort);
                // now that the dialog is set up, it's time to show it
                dialog.show();
                return true;
            case R.id.addsprint_backlog:
                Log.i(Constants.LOGTAG, "Lista["
                        + datos.get(info.position).getDes() + "]: a�adir sprint pulsada!");
                selectedContextMenu = info.position;
                progressDialog = ProgressDialog.show(ctx, "Conectando...",
                        " Obteniendo listado colaboradores", true, false);
                new Thread() {
                    public void run() {
                        SharedPreferences prefs = PreferenceManager
                                .getDefaultSharedPreferences(ctx);
                        String URLFrontController = prefs.getString(
                                Constants.KEY_URL_PREFERENCE, "");
                        String urlRest = URLFrontController + ";jsessionid="
                                + application.getSessionID() + "?action="
                                + Protocol.L_COLAB_PROD + "&value="
                                + application.getProductoSeleccionado();

                        Log.i(Constants.LOGTAG, "Le envio al server: " + urlRest);
                        JsonReader reader = UtilNetwork.getJSON(urlRest);
                        ListColabAll listJSON = new Gson().fromJson(reader,
                                ListColabAll.class);

                        application.setColabAll(listJSON.getAllColab());
                        for (ColaboradorJSON c : application.getColabAll())
                            Log.i(Constants.LOGTAG,
                                    "Recibo del server el colaborador: "
                                            + c.getNombre());
                        handler.sendEmptyMessage(1);
                    }
                }.start();

                return true;
            case R.id.see_backlog:
    			Log.i(Constants.LOGTAG, "Lista["
    					+ datos.get(info.position).getDes()
    					+ "]: detalles pulsada!");

    			dialog = new Dialog(BacklogActivity.this);
    			dialog.setContentView(R.layout.taskdetails);
    			dialog.setTitle(datos.get(info.position).getDes());
    			dialog.setCancelable(true);
    			// there are a lot of settings, for dialog, check them all out!

    			// set up text
    			 TextView typeDetails = (TextView)
    			 dialog.findViewById(R.id.TyeTaskDetails);
    			 //
    			 Log.i(Constants.LOGTAG,"TIPO: "+datos.get(info.position).getTipo());
    			 if(datos.get(info.position).getTipo().equals("analisis")){
    			 typeDetails.setText("Tipo análisis");
    			
    			 }
    			 if(datos.get(info.position).getTipo().equals("prueba")){
    			 typeDetails.setText("Tipo prueba");
    			
    			 }
    			 if(datos.get(info.position).getTipo().equals("reunion")){
    			 typeDetails.setText("Tipo reunión");
    			
    			 }
    			 if(datos.get(info.position).getTipo().equals("prototipado")){
    			 typeDetails.setText("Tipo prototipado");
    			
    			 }
    			 if(datos.get(info.position).getTipo().equals("codificacion")){
    			 typeDetails.setText("Tipo codificación");
    			
    			 }
    			 TextView colDetails = (TextView) dialog
    						.findViewById(R.id.CollaboratorTaskDetails);
    			if (datos.get(info.position).getColabName() != null) {
    				
    				colDetails.setText("Colaborador: "
    						+ datos.get(info.position).getColabName());
    			}else{
    				
    				colDetails.setVisibility(1);
    				
    			}
    			TextView startDetails = (TextView) dialog
    					.findViewById(R.id.StartTaskDetails);
    			DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    			if (datos.get(info.position).getFecini() != null) {
    				String fini = format.format(datos.get(info.position)
    						.getFecini());
    				
    				startDetails.setText("Iniciado en " + fini);
    			}else{
    				
    				startDetails.setVisibility(1);
    				
    			}
    			TextView endDetails = (TextView) dialog
    					.findViewById(R.id.EndTaskDetails);
    			if (datos.get(info.position).getFecfin() != null) {
    				String ffin = format.format(datos.get(info.position)
    						.getFecfin());

    				
    				endDetails.setText("Acabado en " + ffin);
    			}else{
    				
    				endDetails.setVisibility(1);
    				
    				
    			}
    			TextView statusDetails = (TextView) dialog
    					.findViewById(R.id.StatusTaskDetails);

    			if (datos.get(info.position).getEstado() == 1) {

    				statusDetails.setText("To do");
    			}
    			if (datos.get(info.position).getEstado() == 2) {

    				statusDetails.setText("Doing");
    			}
    			if (datos.get(info.position).getEstado() == 3) {

    				statusDetails.setText("Done");
    			}
    			TextView sprintDetails = (TextView) dialog
    					.findViewById(R.id.SprintTaskDetails);
    			if (datos.get(info.position).getSprint() != null) {
    				sprintDetails.setText(datos.get(info.position).getSprint());
    			} else {
    				sprintDetails.setText("Sin asignar a sprint");

    			}
    			//
    			//
    			// set up button
    			Button button = (Button) dialog
    					.findViewById(R.id.BtExitTaskDetails);
    			button.setOnClickListener(mExitTaskDetails);
    			// now that the dialog is set up, it's time to show it
    			dialog.show();

                return true;
            case R.id.del_backlog:
                Long tareaID = datos.get(info.position).getId();
                String urlRest = URLFrontController
                        + ";jsessionid=" + application.getSessionID() + "?action="
                        + Protocol.REMOVE_TAREA + "&value=" + tareaID;

                UtilNetwork.getJSON(urlRest);
                datos.remove(info.position);
                ArrayAdapter<TareaJSON> adapter = new BacklogAdapter(this,
                        getTask());
                setListAdapter(adapter);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.backlogmenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.newtaskoption:
                startActivity(new Intent(BacklogActivity.this,
                        NewTaskActivity.class));

                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    OnClickListener mExitTaskDetails = new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }

    };

    OnClickListener mAddEffort = new OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText ef = (EditText) dialog.findViewById(R.id.ETEffort);
            String esf = ef.getText().toString();
            String urlRest = URLFrontController + ";jsessionid="
                    + application.getSessionID() + "?action=" + Protocol.ADD_ESF
                    + "&value=" + datos.get(info.position).getId() + "&esf=" + esf;

            UtilNetwork.getJSON(urlRest);
            dialog.dismiss();
        }

    };

}
